package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.es.ApArticleSearch;
import com.heima.article.es.ApArticleSearchRepository;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IAsyncService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 请不要叫我高司令
 * @Date 2022/4/15 22:30
 * @Version 1.0
 */

@Service
public class AsyncServiceImpl implements IAsyncService {

    @Autowired
    private Configuration configuration;


    @Autowired
    @Lazy
    private IApArticleService articleService;

    @Autowired
    private MinIOService minIOService;

    @Async
    @Override
    public void createHtml(ApArticle article, String content) {

        try {
            System.out.println(Thread.currentThread().getName() + "生成静态html服务开始执行");
            //获取模板
            Template template = configuration.getTemplate("article.ftl");
            //写入数据
            Map<String, Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));

            //合并模板和数据
            StringWriter out = new StringWriter();
            template.process(map, out);

            //生成静态页面上传到minIO
            String objectName = article.getId() + ".html";
            InputStream is = new ByteArrayInputStream(out.toString().getBytes());
            //上传之前先下载
            minIOService.delete(objectName);
            String url = minIOService.upload(objectName, is, "text/html");
            //需要将生成的url存入article中
            article.setStaticUrl(url);
            articleService.updateById(article);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private ApArticleSearchRepository repository;


    @Async
    @Override
    public void createIndex(ApArticle apArticle) {

        ApArticleSearch search = new ApArticleSearch();
        BeanUtils.copyProperties(apArticle, search);
        repository.save(search);

    }

    @Async
    @Override
    public void updateIndex(ApArticle apArticle) {

        ApArticleSearch search = new ApArticleSearch();
        BeanUtils.copyProperties(apArticle, search);
        repository.save(search);


    }
}
